package com.xin.data.simbapesa.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.adapter.MsgAdapter;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseBindingAdapter1;
import com.xin.data.simbapesa.base.BaseParams;
import com.xin.data.simbapesa.databinding.SimbaFeedbackLineActivityBinding;
import com.xin.data.simbapesa.obj.SimbaChatInfo;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.ResUtils;
import com.xin.data.simbapesa.utils.SpUtils;
import com.xin.data.simbapesa.utils.Tools;
import com.xin.data.simbapesa.utils.ViewUtils;
import com.xin.data.simbapesa.view.SimbaSpaceItemDecoration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class SimbaFeedbackOnlineActivity extends BaseActivity<SimbaFeedbackLineActivityBinding> {


    int code;

    MsgAdapter adapter;

    List<SimbaChatInfo> dataList;

    int page = 1;
    final int size = 20;

    boolean isLoad;

    private final int TIME_WHAT = 1;

    private final int TIME_WHAT1 = 2;


    @Override
    protected SimbaFeedbackLineActivityBinding initViewBinding(LayoutInflater inflater) {
        return SimbaFeedbackLineActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        code = getIntent().getIntExtra("code", 1);


        binding.tvInput.setType(PU.P211);

        dataList = new ArrayList<>();
        adapter = new MsgAdapter(dataList);
        adapter.setCode(code);
        adapter.setOnBtnItem3ClickListener((item, position) -> {
            PU.userBuriedPoint(PU.P203 + (position + 1) + "_CLICK", "");
            Tools.hideSoftInputFromWindow(getActivity(), binding.tvInput);
            if (item.equals(ResUtils.s(R.string.msgtitle_title17))) {
                addChat(item);
                Message msg = new Message();
                msg.what = TIME_WHAT1;
                Bundle data = new Bundle();
                data.putBoolean("isPhone", true);
                msg.setData(data);
                mHandler.sendMessageDelayed(msg, 5000);
            } else {
                addChat(item);
                feedbackTalk(item, "USER");
            }
            Tools.hideSoftInputFromWindow(getActivity(), binding.recyclerView);
        });
        adapter.setOnBtnItemClickListener(new BaseBindingAdapter1.BtnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Tools.hideSoftInputFromWindow(getActivity(), binding.recyclerView);
            }
        });
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager1);
        int d = ResUtils.d(R.dimen.dp_8);
        binding.recyclerView.addItemDecoration(new SimbaSpaceItemDecoration(d, d, getActivity()));
        binding.recyclerView.setAdapter(adapter);
        binding.tvBtn.setOnClickListener(v -> {
            PU.userBuriedPoint(PU.P204, "");
            String data = binding.tvInput.getText().toString();
            if (!TextUtils.isEmpty(data)) {
                ViewUtils.viewScale(v);
                Tools.hideSoftInputFromWindow(getActivity(), binding.tvInput);
                addChat(data);
                feedbackTalk(data, "USER");
                binding.tvInput.setText("");
            }

        });
        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager != null && layoutManager.findFirstCompletelyVisibleItemPosition() == 0 && !isLoad) {
                    page = page + 1;
                    feedbackTalk1();
                }
            }
        });
        binding.recyclerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Tools.hideSoftInputFromWindow(getActivity(), binding.recyclerView);
            }
        });
        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });

    }

    @Override
    protected void initData() {

        UP_TYPE1 = PU.P201;
        UP_TYPE2 = PU.P202;

        SimbaChatInfo chat1 = new SimbaChatInfo();
        chat1.setTalkInfo(ResUtils.s(R.string.feedback1_chat1));
        chat1.setTalkType("CS");

        SimbaChatInfo chat2 = new SimbaChatInfo();
        chat2.setTalkType("");

        dataList.add(chat1);
        dataList.add(chat2);
        adapter.updateAllData();


        page = 1;
        feedbackTalk1();

    }

    void addChat(String data) {
        removeHit();
        SimbaChatInfo chat = new SimbaChatInfo();
        chat.setTalkType("USER");
        chat.setTalkInfo(data);
        chat.setState(0);
        chat.setPhone(false);
        dataList.add(chat);
        adapter.updateAllData();
        binding.recyclerView.scrollToPosition(dataList.size() - 1);
    }

    void removeHit() {
        List<SimbaChatInfo> list = new ArrayList<>();
        for (SimbaChatInfo chat : dataList) {
            if (!TextUtils.isEmpty(chat.getTalkType())) {
                list.add(chat);
            }
        }
        dataList.clear();
        dataList.addAll(list);
        adapter.updateAllData();
    }


    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == TIME_WHAT) {
                if (getActivity() != null && !isFinishing() && !isDestroyed()) {
                    String talkInfo1;
                    Random random = new Random();
                    int index = random.nextInt(3);
                    if (index == 0) {
                        talkInfo1 = ResUtils.s(R.string.feedback1_chat2);
                    } else if (index == 1) {
                        talkInfo1 = ResUtils.s(R.string.feedback1_chat3);
                    } else {
                        talkInfo1 = ResUtils.s(R.string.feedback1_chat4);
                    }
                    feedbackTalk(talkInfo1, "CS");
                }
            } else if (msg.what == TIME_WHAT1) {
                boolean isPhone = msg.getData().getBoolean("isPhone");
                SimbaChatInfo chat1 = new SimbaChatInfo();
                chat1.setPhone(isPhone);
                chat1.setTalkType("CS");
                dataList.add(chat1);

                for (SimbaChatInfo chatInfo : dataList) {
                    chatInfo.setState(1);
                }

                adapter.updateAllData();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeMessages(TIME_WHAT);
            mHandler = null;
        }
    }

    void feedbackTalk(String talkInfo, final String talkType) {
        String token = SpUtils.get_string(this, SpUtils.KEY_TOKEN, "");
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[84], U.URL_MAIN_PRODUCT, token);
        json.addProperty("handleType", "TALK_INPUT");
        json.addProperty("talkType", talkType);
        json.addProperty("talkInfo", talkInfo);
        json.addProperty("page", page);
        json.addProperty("size", size);


        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_MAIN_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }

        String data = AESCryptUtilJar.encryptDefault(json.toString());

        LogUtil.e("me", json + "<-feedbackTalk post->" + data);

        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "<-feedbackTalk json->" + json1);
                            if (JsonParse.getCode(json1)) {
                                boolean cs = !TextUtils.isEmpty(talkType) && talkType.equalsIgnoreCase("CS");
                                if (cs) {
                                    page = 1;
                                    feedbackTalk1();
                                }
                                if (!cs && mHandler != null) {
                                    mHandler.sendEmptyMessageDelayed(TIME_WHAT, 5000);
                                }
                            } else {
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.start_net_failed));
                        LogUtil.e("me", page + "<-feedbackTalk e->" + e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    void feedbackTalk1() {

        isLoad = true;

        showLoading("");
        String token = SpUtils.get_string(this, SpUtils.KEY_TOKEN, "");
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[84], U.URL_MAIN_PRODUCT, token);
        json.addProperty("handleType", "TALK_SELECT");
        json.addProperty("page", page);
        json.addProperty("size", size);

        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_MAIN_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }

        String data = AESCryptUtilJar.encryptDefault(json.toString());

        LogUtil.e("me", json + "<-feedbackTalk1 post->" + data);

        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s) && binding != null) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", page + "<-feedbackTalk1 json->" + json1);
                            if (JsonParse.getCode(json1)) {
                                if (page == 1) {
                                    dataList.clear();
                                }
                                List<SimbaChatInfo> chatList = JsonParse.feedbackTalkJson2Obj(json1);
                                if (chatList != null) {
                                    LogUtil.e("me", "chatList->" + chatList.size());
                                    Collections.sort(chatList, (o1, o2) -> {
                                        long d1 = Long.parseLong(o1.getCreateTimeStamp());
                                        long d2 = Long.parseLong(o2.getCreateTimeStamp());
                                        if (d2 > d1) {
                                            return -1;
                                        } else {
                                            return 1;
                                        }
                                    });
                                    dataList.addAll(0, chatList);
                                }

                                if (dataList.size() == 1) {
                                    SimbaChatInfo chat2 = new SimbaChatInfo();
                                    chat2.setTalkType("");
                                    dataList.add(chat2);
                                }

                                adapter.updateAllData();

                                if (page == 1) {
                                    binding.recyclerView.scrollToPosition(dataList.size() - 1);
                                }

                                if (dataList.isEmpty()) {
                                    feedbackTalk(ResUtils.s(R.string.feedback1_chat1), "CS");
                                }

                            } else {
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                            }
                        }
                        isLoad = false;
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        hideLoading();
                        isLoad = false;
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.start_net_failed));

                        LogUtil.e("me", page + "<-feedbackTalk1 e->" + e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}
